package besta.moon.sql.expression.function;

import besta.moon.sql.datatype.MutableNumeric;
import besta.moon.sql.expression.ExpressionArithmetic;
import besta.moon.sql.parser.SQLTokenizer;
import besta.moon.util.MoonUtils;

public abstract class FunctionReturnP1Number extends FunctionReturnP1 {

    @Override
    public final boolean getBoolean() throws Exception {
        return getDouble() != 0;
    }

    @Override
    public final int getInt() throws Exception {
        return MoonUtils.long2int(getLong());
    }

    @Override
    public final long getLong() throws Exception {
        return MoonUtils.double2long(getDouble());
    }

    @Override
    public final float getFloat() throws Exception {
        return (float) getDouble();
    }

    @Override
    public MutableNumeric getNumeric() throws Exception {
        if (param1.isNull()) {
            return null;
        }
        switch (getDataType()) {
            case SQLTokenizer.INT:
                return new MutableNumeric(getInt());
            case SQLTokenizer.BIGINT:
                return new MutableNumeric(getLong());
            case SQLTokenizer.MONEY:
                return new MutableNumeric(getMoney(), 4);
            case SQLTokenizer.DECIMAL:
                MutableNumeric num = param1.getNumeric();
                num.floor();
                return num;
            case SQLTokenizer.DOUBLE:
                return new MutableNumeric(getDouble());
            default:
                throw new Error();
        }
    }

    @Override
    public long getMoney() throws Exception {
        return MoonUtils.doubleToMoney(getDouble());
    }

    @Override
    public String getString() throws Exception {
        if (isNull()) {
            return null;
        }
        return getObject().toString();
    }

    @Override
    public final int getDataType() {
        return ExpressionArithmetic.getBestNumberDataType(param1.getDataType());
    }

}
